<template>
  <div class="course-image">
      <el-form-item :label="label">
          <el-progress v-if="isUpload" type="circle" :width="178" :percentage="precentage"></el-progress>
            <el-upload
            v-show="!isUpload"
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="handleUpload"
              :on-progress="handleProgress"
              :status="precentage === 100 ? 'success' : undefined"
            >
              <img v-if="value" :src="value" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
  </div>
</template>

<script>
import { uploadCourseImage } from '@/services/course'

export default {
  name: 'course-image',
  data () {
    return {
      isUpload: false,
      precentage: 0
    }
  },
  props: ['value', 'label'],
  methods: {
    handleProgress (event, file) {
      console.log(event, file)
    },
    async handleUpload (option) {
      this.isUpload = true
      const fd = new FormData()
      fd.append('file', option.file)
      const { data } = await uploadCourseImage(fd, event => {
        this.precentage = Math.floor(event.loaded / event.total * 100)
      })
      if (data.code === '000000') {
        this.$emit('input', data.data.name)
        this.isUpload = false
        this.precentage = 0
      }
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
